package com.company.common.encrypt;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSAUtil {
    /**
     * RSA私钥解密
     */
    public static String decrypt(String pw) throws Exception{
        String privateKey =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCML8mVAUnF0AgKOhNrae7taym1cjZD66clrT" +
                "5aXy9LRc8e1bU0ZycReQpYPn7RaRC+1IdQuWrXws+rwGkOSGzeIUV/1viYYVE7Hc+x4HBFPbT9qebK4jZ/7JCF" +
                "hf60WkYrxMTrGi7LIRG28LzeuiWAlaRMpskqT85hlo3Ks8EkNzgH6os7nxf4cPPPRTcpJlYwB7zOBOODfsH8Bt" +
                "A3E3W1k8AqVjhrGs8GtB92sjHzHx/g2FW7PndGrvxHgTv3ey9r0GP2X2wMMlJMbMmkUSa/lf4jdQN2xDlwV8rd" +
                "GNMTRvtYv0PqusPmBYcC/3Pi7TWS2XNcgEJpDiyHTCBcIRcVAgMBAAECggEASvnH+2x781Mm6alT94/pnItC/G" +
                "tAQKVJeSol/hmIZt7IPrqXtpYw2/R7puSN2RwzO4zZbkAst4bWoQpAZcYwi8EJtazYuk7aLh7slTrvcOjm4wA6" +
                "kmnYMiToyrD2n6jkfMY5d3BCdJuUKN6qdQjjw9jEzcYqMvoJ7EGkRjRLaT1cc0qMCQGhDdj+vRNnoqp1FgYpxQ/" +
                "mEfc1TTRwvlUPiWgwefxqP7AU0bXbwpuwXcN+crjV64adgnDiYpowaH/OhEOmcedWP/8UJiBH6BoolCAtIYBt0" +
                "3m7nlvYUtgcB8dpVIxsrhAt/hmBeH8KpjGdu6otrTblV104tm339mQJIQKBgQDnuNvfqXQq6+luyaiDM5vCZZy" +
                "u5BUQz8P5+lwPmZS2iZRT0qh24kD6t7kqzUqJSZfgowcznfMRLLHwU8L2Il0TLrr/TQax/lGQWpciU9EVT+1mv" +
                "stu2dwe+X+FwsjWnFnEKexKprnAd9QuWyfInxrj380AGMyIpQHEf62xp+XhiQKBgQCa387oMcixCAtpbaEq5+A" +
                "iTZyYsi0Iry1q1LcHu4HYLvUtU0weglsFD9XZijcPgkH0sQ0+rwNN53V/6JQ/Xvym9qc/xEqUGEEIfTMWvkujO" +
                "NxyA/kDNnJyw73Rhl+9tmRdzCzz8e04WcDnDgRFc07TK0ZJCgr8SvUOWdLeptJiLQKBgGCeJZ+mijdzUkvNbaP" +
                "3GtT9hU0u8NGnr7FFgKlIgkdyKhShW3jmce2YOW7tVkzUEK2rjE8rZrQcjL0GT95NCb372CCnP0lsHxovi6DWj" +
                "fFy+CvFFhHMaQnJQjDFvPQvEQbH7CxcREtKK4CApZ/zJ0UohdOqg23eT1RdYFEZDrLxAoGAGlK99SM5DDXk0qe" +
                "KhCNjKhFs81sdYmN74bOD5HGPUTIyA+Erh+f6FnMpks72KtGl6jQJn0TZ1+zmQLZEND0tzicQKDtxvZgdvZaiD" +
                "1SKwJRSi6J3OX+QlkcExU8EiNcuWe7xGQlem3xN2De+rBs8I5IwYQuu8FDBNA46VBOgoIUCgYBNUOXQx7DyAKk" +
                "5ui/H7cr98NeGQFFF0Aq8V6kuVq8nFVPjH1zq8JDtvmkB/Bo99+34fMJV0f3+H1p2nvAOxUNFPgoRUNy9u9jdj" +
                "riHJeXrK8oSIe28IJnfNRibgdZlM3MthDnhJ/9Vgs4ukhmC34VzsytXWfFDlpQDT+OaB7TZIg==";

        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(pw.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }
}
